package com.lin.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = 5;

    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = 5;

    /**
     * 队列大小
     */
    private static final int QUEUE_CAPACITY = 50;

    /**
     * 线程池中的线程的名称前缀
     */
    private static final String THREAD_NAME_PREFIX = "lin-executor-";

    @Bean
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 配置核心线程数
        executor.setCorePoolSize(CORE_POOL_SIZE);
        // 配置最大线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        // 配置队列大小
        executor.setQueueCapacity(QUEUE_CAPACITY);
        // 配置线程池中的线程名称前缀
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        // 配置线程拒绝策略，设置为CallerRunsPolicy，当线程队列都满了，由发起线程的主线程自己执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("线程池执行任务发送未知错误, 执行方法：{}", method.getName(), ex);
    }
}
